/**
 * 
 */
package com.ctrip.cap.internal.appium.test;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.ios.IOSDriver;

import java.net.URL;

import org.openqa.selenium.Capabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.AppiumContext;
import com.ctrip.cap.device.Device;
import com.ctrip.cap.device.ios.IOSDevice;
import com.ctrip.cap.internal.appium.suite.AppiumSuiteListener;
import com.ctrip.cap.internal.domain.Context;
import com.ctrip.cap.internal.performance.Profilers;
import com.ctrip.cap.internal.test.MethodFilter;
import com.ctrip.cap.lanucher.AppiumConfig;
import com.ctrip.cap.lanucher.AppiumServer;

/**
 * @author zwxu
 *
 */
public class PrepareIOSDriver implements MethodFilter {
	private static final Logger logger = LoggerFactory
			.getLogger(PrepareAppiumDriver.class);

	@Override
	public void doFilter(Context contextObj) {
		AppiumContext context = (AppiumContext) contextObj;

		Device device = (IOSDevice) context.getDevice();
		AppiumConfig appiumConfig = context.getAppiumConfig();
		appiumConfig.setUdid(device.getSerialNumber());

		AppiumServer appiumServer = AppiumSuiteListener
				.getAppiumServerWithDevice(device);
		context.setAppium(appiumServer);
		if (!appiumServer.isRunning() || appiumConfig.isCaseLevelRestart()) {
			Profilers.preAppium().start("startAppiumServer");
			appiumServer.startAppium();
		}

		URL url = appiumServer.getURL();
		Capabilities capabilities = appiumConfig.toCapabilities();
		logger.info("\nTry connecting to {}\nwith capabilities\n{}", url,
				appiumConfig);
		Profilers.preAppium().start("newWebDriver");

		logger.info("New AppiumDriver may cost 30 seconds or more,have patience ......");
		AppiumDriver driver = new IOSDriver(url, capabilities);
		// driver.manage().timeouts().implicitlyWait(time, unit)
		context.setDriver(driver);

		Profilers.preAppium().stop().log();
	}

}
